package org.example.spring.service;

import com.alibaba.fastjson.JSON;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.common.xcontent.XContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.example.spring.dao.UserMapper;
import org.example.spring.domain.UserEntity;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.query.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.IntStream;

/**
 * @author Tang
 * @classname UserService
 * @description [  ]
 * @date 2023/5/2 13:01
 */
@Service
public class UserServiceImpl implements UserService {

    @Resource
    UserMapper userMapper;

    @Resource
    ElasticsearchOperations elasticsearchOperations;

    @Override
    public UserEntity getOne(Integer id) {
        final Optional<UserEntity> optionalUserEntity = userMapper.findById(id.longValue());
        return optionalUserEntity.orElseGet(UserEntity::new);
    }

    public List<UserEntity> findAll() {
        final NativeSearchQuery searchQuery = new NativeSearchQuery(QueryBuilders.matchAllQuery());
        searchQuery.setPageable(PageRequest.of(0, 10));
        return elasticsearchOperations.queryForList(searchQuery, UserEntity.class);
    }

    public void insertBatch() {
        List<IndexQuery> queries = new ArrayList<>(1000);
        LocalDateTime localDate = LocalDateTime.now();
        IntStream.range(0,10)
                .forEach((id) -> {
                    final UserEntity user = new UserEntity();
                    user.setAge(id);
                    user.setName("tang" + id);
                    int num = -10 + new Random().nextInt(20);
                    user.setBirth(Date.from(localDate.plusDays(Long.parseLong(num+"")).toInstant(ZoneOffset.UTC)));
                    user.setTitle("这是title-" + num);
                    final IndexQuery indexQuery = new IndexQueryBuilder()
                            .withId(String.valueOf(id))
                            .withObject(user)
                            .build();
                    queries.add(indexQuery);
                });
        elasticsearchOperations.bulkIndex(queries);
    }

    public static void main(String[] args) {
        System.out.println(LocalDate.now().plusDays(2).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
    }

    public void updatePart() {
        UserEntity userEntity = new UserEntity();
        userEntity.setId(3);
        userEntity.setAge(90);
        userEntity.setTitle("更新过后的title");
        userEntity.setName("更新的name");

        final UpdateRequest updateRequest = new UpdateRequest("users","3");
        Map<String, Object> updateMap = new HashMap<>(8);
        updateMap.put("title", userEntity.getTitle());
        updateMap.put("age", userEntity.getAge());
        updateRequest.doc(updateMap);

        final UpdateQuery updateQuery = new UpdateQueryBuilder()
                .withId("3")
                .withClass(UserEntity.class)
                .withIndexName("users")
                .withUpdateRequest(updateRequest)
                .build();

        elasticsearchOperations.update(updateQuery);
    }

}
